package com.tegtech.tools.aws.support;

import java.util.ArrayList;

import com.tegtech.tools.aws.properties.AwsProperties;

import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.Delete;
import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;

/**
 * S3对象存储支持类
 * @Author Jun
 * @date 2021年3月5日 下午3:26:56
 */
public class S3Files {

	private static S3Client s3;

	static {
		if(s3 == null) {
			s3 = S3Client.builder()
					.region(AwsProperties.s3Region)
					.credentialsProvider(StaticCredentialsProvider.create(AwsProperties.awsBasicCredentials))
					.build();
		}
	}

	/**
	 * 获取文件头信息
	 * @param key
	 * @return
	 */
	public static HeadObjectResponse getHeadObject(String key) {
		HeadObjectRequest objectRequest = HeadObjectRequest.builder().key(key).bucket(AwsProperties.getS3Bucket()).build();
		return s3.headObject(objectRequest);
	}
	
	/**
	 * 删除文件
	 * @param keys
	 */
	public static void deleteObjects(String ... keys) {
		ArrayList<ObjectIdentifier> toDelete = new ArrayList<ObjectIdentifier>();
	    for (int i = 0; i < keys.length; i++) {
	    	toDelete.add(ObjectIdentifier.builder().key(keys[i]).build());
		}
	    DeleteObjectsRequest dor = DeleteObjectsRequest.builder()
                .bucket(AwsProperties.getS3Bucket())
                .delete(Delete.builder().objects(toDelete).build())
                .build();
        s3.deleteObjects(dor);
	}

}
